use axum::{body::Body, extract::State, http::Response, response::IntoResponse, Json};
use sky_pojo::{dto::shopping::ShoppingCartDTO, entities};

use crate::{bootstrap::AppState, middleware::jwt::user::Claims, router::resp::RespVO, service};

pub async fn add(
    State(state): State<AppState>,
    claims: Claims,
    Json(dto): Json<ShoppingCartDTO>,
) -> Response<Body> {
    tracing::info!("购物车添加：{:?}", dto);
    match service::shopping::add_shopping_cart(&state.db_pool, claims.id, dto).await {
        Ok(model) => RespVO::<entities::shopping_cart::Model>::success("".to_owned(), Some(model))
            .into_response(),
        Err(e) => RespVO::<()>::error_without_data(e).into_response(),
    }
}

pub async fn list(State(state): State<AppState>, claims: Claims) -> Response<Body> {
    match service::shopping::list(&state.db_pool, claims.id).await {
        Ok(vec) => RespVO::<Vec<entities::shopping_cart::Model>>::success("".to_owned(), Some(vec))
            .into_response(),
        Err(e) => RespVO::<()>::error_without_data(e).into_response(),
    }
}

pub async fn sub(
    State(state): State<AppState>,
    claims: Claims,
    Json(dto): Json<ShoppingCartDTO>,
) -> Response<Body> {
    service::shopping::sub_shoppingcart(&state.db_pool, dto, claims.id).await;
    RespVO::<()>::success_without_data("Ok".to_owned()).into_response()
}

pub async fn clean(State(state): State<AppState>, claims: Claims) -> Response<Body> {
    match service::shopping::clean_shopping_cart(&state.db_pool, claims.id).await {
        Ok(effect_rows) => {
            RespVO::<u64>::success("success".to_owned(), Some(effect_rows)).into_response()
        }
        Err(e) => RespVO::<()>::error_without_data(e).into_response(),
    }
}
